# Script to run moving window regressions and produce figure
library(dplyr)
library(magrittr)
library(tidyr)
library(ggplot2)

# redo this with recent area data (v9 reduced)
dat <- rio::import("data/LandCover_GRID_CELL_v9_reduced.dta")

dat %<>%
  mutate(country_area_ln = log(area + 1))

regs_df <- data.frame(start_year = 1789:1990,
                      end_year = 1818:2019,
                      coef = NA,
                      se = NA,
                      t_value = NA,
                      N = NA,
                      r2 = NA, 
                      series = "lexical")

for (i in 1:nrow(regs_df)){
  subset_data <- dat[which(dat$year %in% c(regs_df$start_year[i]:regs_df$end_year[i])), ]
  reg <- lm(v2x_polyarchy_imp_100 ~ country_area_ln + portdist_natural + as.factor(year),
            data = subset_data)
  reg_sum <- summary(reg)
  regs_df$coef[i] <- reg_sum$coefficients[2, 1]
  regs_df$se[i] <- reg_sum$coefficients[2, 2]
  regs_df$t_value[i] <- reg_sum$coefficients[2, 3]
  regs_df$N[i] <- length(reg_sum$residuals)
  regs_df$r2[i] <- reg_sum$r.squared
}

regs_df$year <- regs_df$end_year - 15

g <- regs_df %>%
  filter(series == "lexical") %>%
  ggplot(aes(x = year)) +
  geom_ribbon(aes(ymin = coef - se,
                  ymax = coef + se),
              color = 'lightgray',
              alpha = 0.25) +
  geom_hline(yintercept = 0) + 
  geom_point(aes(y = coef)) +
  scale_x_continuous(breaks = seq(1800, 2025, by = 25)) +
  # ylim(0, 0.04) + 
  labs(x = "Year",
       y = "Coefficient estimates for Country Area") +
  theme(panel.grid.minor = element_blank(),
        panel.background = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_blank(),
        axis.line = element_line(color = "black", ),
        plot.margin = margin(1, 1, 1, 0.25, "cm"),
        axis.text = element_text(size = 11),
        axis.title = element_text(size = 12))

## ggsave(plot = g, filename = "figure_7_4.png",
##        width = 11, height = 8.5)

ggsave(plot = g, filename = "output/figure_7_4.tiff",
       width = 11, height = 8.5, dpi = 300)
